<?php

namespace App\Http\Controllers\Tenant;

use App\Http\Controllers\Controller;
use App\Models\Freelancer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class FreelancerProfileController extends Controller
{
    /**
     * 获取个人资料
     */
    public function show(Request $request)
    {
        $freelancer = $request->user();
        
        return response()->json([
            'success' => true,
            'data' => [
                'freelancer' => $freelancer->makeHidden(['password'])
            ]
        ]);
    }

    /**
     * 更新基本信息
     */
    public function updateBasicInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:20',
            'address' => 'sometimes|string|max:500',
            'bio' => 'sometimes|string|max:1000',
            'skills' => 'sometimes|array',
            'skills.*' => 'string|max:100',
            'experience_years' => 'sometimes|integer|min:0|max:50',
            'education' => 'sometimes|in:high_school,college,bachelor,master,doctor',
            'languages' => 'sometimes|array',
            'languages.*' => 'string|max:50',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer = $request->user();

        // 如果修改了手机号，需要检查是否已存在
        if ($request->has('phone') && $request->phone !== $freelancer->phone) {
            $existingFreelancer = Freelancer::where('phone', $request->phone)
                ->where('id', '!=', $freelancer->id)
                ->first();

            if ($existingFreelancer) {
                return response()->json([
                    'success' => false,
                    'message' => '手机号已被其他用户使用'
                ], 400);
            }
        }

        try {
            $updateData = $request->only([
                'name', 'phone', 'address', 'bio', 'skills', 
                'experience_years', 'education', 'languages'
            ]);

            // 将数组字段转换为JSON
            if (isset($updateData['skills'])) {
                $updateData['skills'] = json_encode($updateData['skills']);
            }
            if (isset($updateData['languages'])) {
                $updateData['languages'] = json_encode($updateData['languages']);
            }

            $freelancer->update($updateData);

            return response()->json([
                'success' => true,
                'message' => '基本信息更新成功',
                'data' => [
                    'freelancer' => $freelancer->fresh()->makeHidden(['password'])
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 上传头像
     */
    public function uploadAvatar(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'avatar' => 'required|image|mimes:jpeg,png,jpg,gif|max:2048', // 2MB
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer = $request->user();

        try {
            // 删除旧头像
            if ($freelancer->avatar) {
                Storage::disk('public')->delete($freelancer->avatar);
            }

            // 上传新头像
            $avatarPath = $request->file('avatar')->store('freelancer/avatars', 'public');

            $freelancer->update([
                'avatar' => $avatarPath
            ]);

            return response()->json([
                'success' => true,
                'message' => '头像上传成功',
                'data' => [
                    'avatar_url' => Storage::disk('public')->url($avatarPath)
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '头像上传失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 上传身份证照片
     */
    public function uploadIdCard(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id_card_front' => 'sometimes|image|mimes:jpeg,png,jpg|max:5120', // 5MB
            'id_card_back' => 'sometimes|image|mimes:jpeg,png,jpg|max:5120', // 5MB
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer = $request->user();
        $updateData = [];

        try {
            // 上传身份证正面
            if ($request->hasFile('id_card_front')) {
                if ($freelancer->id_card_front) {
                    Storage::disk('public')->delete($freelancer->id_card_front);
                }
                $frontPath = $request->file('id_card_front')->store('freelancer/id_cards', 'public');
                $updateData['id_card_front'] = $frontPath;
            }

            // 上传身份证背面
            if ($request->hasFile('id_card_back')) {
                if ($freelancer->id_card_back) {
                    Storage::disk('public')->delete($freelancer->id_card_back);
                }
                $backPath = $request->file('id_card_back')->store('freelancer/id_cards', 'public');
                $updateData['id_card_back'] = $backPath;
            }

            if (!empty($updateData)) {
                // 重新设置验证状态为待审核
                $updateData['verification_status'] = 'pending';
                $freelancer->update($updateData);
            }

            return response()->json([
                'success' => true,
                'message' => '身份证照片上传成功，请等待审核',
                'data' => [
                    'id_card_front_url' => isset($updateData['id_card_front']) ? Storage::disk('public')->url($updateData['id_card_front']) : null,
                    'id_card_back_url' => isset($updateData['id_card_back']) ? Storage::disk('public')->url($updateData['id_card_back']) : null,
                ]
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '身份证照片上传失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 更新银行卡信息
     */
    public function updateBankInfo(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'bank_name' => 'required|string|max:100',
            'bank_account' => 'required|string|max:30',
            'bank_account_name' => 'required|string|max:100',
        ]);

        if ($validator->fails()) {
            return response()->json([
                'success' => false,
                'message' => '验证失败',
                'errors' => $validator->errors()
            ], 422);
        }

        $freelancer = $request->user();

        try {
            $freelancer->update([
                'bank_name' => $request->bank_name,
                'bank_account' => $request->bank_account,
                'bank_account_name' => $request->bank_account_name,
            ]);

            return response()->json([
                'success' => true,
                'message' => '银行卡信息更新成功'
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'success' => false,
                'message' => '更新失败，请稍后重试'
            ], 500);
        }
    }

    /**
     * 获取认证状态
     */
    public function getVerificationStatus(Request $request)
    {
        $freelancer = $request->user();
        
        return response()->json([
            'success' => true,
            'data' => [
                'verification_status' => $freelancer->verification_status,
                'verification_note' => $freelancer->verification_note,
                'verified_at' => $freelancer->verified_at,
                'has_id_card_front' => !empty($freelancer->id_card_front),
                'has_id_card_back' => !empty($freelancer->id_card_back),
                'has_bank_info' => !empty($freelancer->bank_account),
            ]
        ]);
    }
}
